package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import server.CacheChangeInfoSender;
import server.HeartBitListener;
import server.HeartBitSender;
import shared.ServerCache;

public class Server extends Thread{

	private List <Socket> connectedClients=new ArrayList <Socket>();
	private CacheChangeInfoSender sender;
	private HeartBitSender heartBitSender;
	private HeartBitListener heartBitListener;
	private ServerCache cache;
	private int timeout=1000;
	private boolean worked;
	
	public Server(int timeout) {
		super();
		this.timeout = timeout;
		this.cache=new ServerCache();
		this.sender=new CacheChangeInfoSender(connectedClients);
		this.heartBitListener=new HeartBitListener(connectedClients);
		this.heartBitListener.start();
		this.heartBitSender=new HeartBitSender(connectedClients, timeout);
		this.heartBitSender.start();
		this.worked=true;
	}
	
	@Override
	public void run() {
		
		try {
			ServerSocket serverSocket=new ServerSocket(2013);
			while (worked){
				Socket connectedClientSocket=serverSocket.accept();
				connectedClientSocket.setSoTimeout(timeout);
				connectedClients.add(connectedClientSocket);
				
			}
		} catch (IOException e) {
			System.out.println("Error on server IO");
		}
	}
	
	public void addInfo(String info){
		this.cache.put(info);
		sender.send(info);
	}
	
	void turnOf(){
		this.heartBitListener.turnOf();
		this.heartBitSender.turnOf();
		this.
		this.worked=false;
	}
}
